package com.michael.retail.auth.controller;

import com.michael.retail.auth.entity.OAuth2TokenVO;
import com.michael.retail.commons.constant.AuthConstant;
import com.michael.retail.commons.pojo.global.R;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.security.Principal;
import java.util.Map;

/**
 * 类功能描述:
 * <pre>
 *   认证中心
 * </pre>
 *
 * @author Michael
 * @version 1.0
 * @date 2021/7/6 11:35
 */
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RequestMapping("/oauth")
public class OAuth2Controller {

    private final TokenEndpoint tokenEndpoint;

    @ApiOperation(value = "OAuth2认证", notes = "login")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "grant_type", defaultValue = "password", value = "授权模式", required = true),
            @ApiImplicitParam(name = "client_id", defaultValue = "client", value = "OAuth2客户端ID", required = true),
            @ApiImplicitParam(name = "client_secret", defaultValue = "123456", value = "OAuth2客户端秘钥", required = true),
            @ApiImplicitParam(name = "refresh_token", value = "刷新token"),
            @ApiImplicitParam(name = "username", defaultValue = "admin", value = "登录用户名"),
            @ApiImplicitParam(name = "password", defaultValue = "123456", value = "登录密码"),
            @ApiImplicitParam(name = "requestId", defaultValue = "123456", value = "请求唯一ID,(验证验证码时需要)"),
            @ApiImplicitParam(name = "validCode", defaultValue = "1234", value = "验证码")
    })
    @PostMapping("/token")
    public R<OAuth2TokenVO> postAccessToken(
            @ApiIgnore Principal principal,
            @ApiIgnore @RequestParam Map<String, String> parameters
    ) throws HttpRequestMethodNotSupportedException {

        // 不同客户端？？？

        OAuth2AccessToken accessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
        OAuth2TokenVO tokenVO = OAuth2TokenVO.builder()
                                             .token(accessToken.getValue())
                                             .refreshToken(accessToken.getRefreshToken().getValue())
                                             .expiresIn(accessToken.getExpiresIn())
                                             .tokenHead(AuthConstant.AUTHORIZATION_PREFIX)
                                             .build();

        return R.succeed(tokenVO);
    }

    //@ApiOperation(value = "OAuth2认证", notes = "login")
    //@ApiImplicitParams({
    //        @ApiImplicitParam(name = "grant_type", defaultValue = "password", value = "授权模式", required = true),
    //        @ApiImplicitParam(name = "client_id", defaultValue = "client", value = "Oauth2客户端ID", required = true),
    //        @ApiImplicitParam(name = "client_secret", defaultValue = "123456", value = "Oauth2客户端秘钥", required =
    //        true),
    //        @ApiImplicitParam(name = "refresh_token", value = "刷新token"),
    //        @ApiImplicitParam(name = "username", defaultValue = "admin", value = "登录用户名"),
    //        @ApiImplicitParam(name = "password", defaultValue = "123456", value = "登录密码")
    //})
    //@GetMapping("/token2")
    ////@PostMapping("/token")
    //public Object postAccessToken2(
    //        @ApiIgnore Principal principal,
    //        @ApiIgnore @RequestParam Map<String, String> parameters
    //) throws HttpRequestMethodNotSupportedException {
    //
    //    /**
    //     * 获取登录认证的客户端ID
    //     *
    //     * 兼容两种方式获取Oauth2客户端信息（client_id、client_secret）
    //     * 方式一：client_id、client_secret放在请求路径中
    //     * 方式二：放在请求头（Request Headers）中的Authorization字段，且经过加密，例如 Basic Y2xpZW50OnNlY3JldA== 明文等于 client:secret
    //     */
    //    String clientId = JwtUtils.getAuthClientId();
    //    OAuth2ClientEnum client = OAuth2ClientEnum.getByClientId(clientId);
    //    switch (client) {
    //        case TEST:
    //            return tokenEndpoint.postAccessToken(principal, parameters).getBody();
    //        case MINWX:
    //            // 微信小程序登录
    //            // weAppServiceImpl.login(parameters)
    //            return R.succeed("小程序登录方式");
    //        default:
    //            new RuntimeException("测试异常");
    //            // 默认后台系统登录
    //            return R.succeed(tokenEndpoint.postAccessToken(principal, parameters).getBody());
    //    }
    //}

    //@ApiOperation(value = "注销", notes = "logout")
    //@PostMapping("/logout")
    //public R logout() {
    //    JSONObject jsonObject = JwtUtils.getJwtPayload();
    //    // JWT唯一标识
    //    String jti = jsonObject.getStr(AuthConstant.JWT_JTI);
    //    // JWT过期时间戳
    //    Long exp = jsonObject.getLong(AuthConstant.JWT_EXP);
    //    if (exp != null) {
    //        long currentTimeSeconds = System.currentTimeMillis() / 1000;
    //        // token已过期，无需加入黑名单
    //        if (exp < currentTimeSeconds) {
    //            return R.succeed();
    //        }
    //        redisTemplate.opsForValue().set(
    //                AuthConstant.TOKEN_BLACKLIST_PREFIX + jti,
    //                null,
    //                (exp - currentTimeSeconds),
    //                TimeUnit.SECONDS
    //        );
    //    } else {
    //        // token 永不过期则永久加入黑名单
    //        redisTemplate.opsForValue().set(AuthConstant.TOKEN_BLACKLIST_PREFIX + jti, null);
    //    }
    //    return R.succeed();
    //}
}
